<?php
// 方弦研究所
namespace app;

/**
 * 文本类
 */
class Text extends Init
{
    /**
     * 解析
     * @return void
     */
    public function parse()
    {
        // 初始化变量
        $config = \fxapp\Base::config('env.base');
        $tray['file'] = $config['root'] . 'static' . DIRECTORY_SEPARATOR . 'obj_collage.inc.php';
        $tray['content'] = file_get_contents($tray['file']);
        // $tray['content'] = substr($tray['content'], 0, 200);
        $tray['data'] = $tray['content'];
        // echo $tray['data'], PHP_EOL;
        // unset($tray['content']);
        // 转存文字文件
        $tray['list'] = [];
        while (true) {
            $tray['pattern'] = '((\\\\[x0-9][a-z0-9]{1,2})+)';
            $tray['result'] = preg_match('/' . $tray['pattern'] . '/', $tray['data'], $tray['value']);
            if ($tray['result'] === 0) break;
            $tray['value'] = $tray['value'][0];
            $tray['list'][] = $tray['value'];
            $tray['data'] = preg_replace('/' . $tray['pattern'] . '/', '', $tray['data'], 1);
        }
        // 输出PHP文件
        $file['file'] = $config['root'] . 'static' . DIRECTORY_SEPARATOR . 'obj_collage.inc.text.php';
        $file['base'] = fopen($file['file'], "w");
        $file['content'] = '<?php' . PHP_EOL;
        foreach ($tray['list'] as $value) {
            $file['content'] .= 'echo \'' . $value . '\', "' . $value . '", PHP_EOL;' . PHP_EOL;
        }
        fwrite($file['base'], $file['content']);
        fclose($file['base']);
        var_dump(date('Y-m-d H:i:s') . '：写入文件');
        // 替换文字
        $tray['data'] = $tray['content'];
        $tray['path'] = $config['web'] . '/static/obj_collage.inc.text.php';
        exec('php "' . $file['file'] . '" 2>&1', $tray['format']);
        foreach ($tray['format'] as $value) {
            $tray['pattern'] = '((\\\\[x0-9][a-z0-9]{1,2})+)';
            $tray['result'] = preg_match('/' . $tray['pattern'] . '/', $value, $tray['value']);
            if ($tray['result'] === 0) continue;
            $tray['value'] = $tray['value'][0];
            $tray['value'] = substr($value, strlen($tray['value']));
            $tray['value'] = str_replace('"', '\"', $tray['value']);
            $tray['data'] = preg_replace('/' . $tray['pattern'] . '/', $tray['value'], $tray['data'], 1);
        }
        // 写入解析文件
        $file['file'] = $config['root'] . 'static' . DIRECTORY_SEPARATOR . 'obj_collage.inc.parse.php';
        $file['base'] = fopen($file['file'], "w");
        $file['content'] = $tray['data'];
        fwrite($file['base'], $file['content']);
        fclose($file['base']);
        echo $tray['data'];
    }
}
